package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.InterviewDTO;
import com.example.joblinker.entity.Interview;
import com.example.joblinker.entity.JobApplication;
import com.example.joblinker.mapper.InterviewMapper;
import com.example.joblinker.mapper.JobApplicationMapper;
import com.example.joblinker.service.InterviewService;
import com.example.joblinker.service.JobApplicationService;
import com.example.joblinker.vo.InterviewVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

@Service
public class InterviewServiceImpl implements InterviewService {

    @Resource
    private InterviewMapper interviewMapper;

    @Resource
    private JobApplicationMapper jobApplicationMapper;

    @Resource
    private JobApplicationService jobApplicationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InterviewVO arrangeInterview(InterviewDTO interviewDTO) {
        // 检查申请记录是否存在
        JobApplication application = jobApplicationMapper.selectById(interviewDTO.getApplicationId());
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }

        // 创建面试
        Interview interview = new Interview();
        BeanUtils.copyProperties(interviewDTO, interview);
        interview.setStatus(0); // 待确认状态
        interviewMapper.insert(interview);

        // 更新申请状态为待面试
        jobApplicationService.updateApplicationStatus(application.getId(), 2, "已安排面试");

        // 转换为VO并返回
        return convertToVO(interview);
    }

    @Override
    public InterviewVO getInterviewDetail(Long id) {
        Interview interview = interviewMapper.selectById(id);
        if (interview == null) {
            throw new RuntimeException("面试记录不存在");
        }
        return convertToVO(interview);
    }

    @Override
    public Page<InterviewVO> getUserInterviews(Long userId, Integer page, Integer size) {
        // 创建分页对象
        Page<Interview> interviewPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Interview> queryWrapper = new LambdaQueryWrapper<Interview>()
                .inSql(Interview::getApplicationId,
                        "SELECT id FROM job_application WHERE user_id = " + userId)
                .orderByDesc(Interview::getInterviewTime);

        // 执行查询
        interviewMapper.selectPage(interviewPage, queryWrapper);

        // 转换结果
        Page<InterviewVO> voPage = new Page<>();
        BeanUtils.copyProperties(interviewPage, voPage, "records");
        voPage.setRecords(interviewPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    public Page<InterviewVO> getCompanyInterviews(Long companyId, Integer page, Integer size) {
        // 创建分页对象
        Page<Interview> interviewPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Interview> queryWrapper = new LambdaQueryWrapper<Interview>()
                .inSql(Interview::getApplicationId,
                        "SELECT ja.id FROM job_application ja " +
                                "LEFT JOIN job j ON ja.job_id = j.id " +
                                "WHERE j.company_id = " + companyId)
                .orderByDesc(Interview::getInterviewTime);

        // 执行查询
        interviewMapper.selectPage(interviewPage, queryWrapper);

        // 转换结果
        Page<InterviewVO> voPage = new Page<>();
        BeanUtils.copyProperties(interviewPage, voPage, "records");
        voPage.setRecords(interviewPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInterviewStatus(Long id, Integer status) {
        // 获取面试记录
        Interview interview = interviewMapper.selectById(id);
        if (interview == null) {
            throw new RuntimeException("面试记录不存在");
        }

        // 更新状态
        interview.setStatus(status);
        interviewMapper.updateById(interview);

        // 如果面试已完成，更新申请状态
        if (status == 2) {
            jobApplicationService.updateApplicationStatus(interview.getApplicationId(), 2, "面试已完成");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitFeedback(Long id, String feedback, Integer rating) {
        // 获取面试记录
        Interview interview = interviewMapper.selectById(id);
        if (interview == null) {
            throw new RuntimeException("面试记录不存在");
        }

        // 更新反馈
        interview.setFeedback(feedback);
        interview.setRating(rating);
        interview.setStatus(2); // 已完成状态
        interviewMapper.updateById(interview);

        // 根据评分更新申请状态
        Integer applicationStatus = rating >= 3 ? 3 : 4; // 3分以上通过，否则拒绝
        String note = rating >= 3 ? "面试通过" : "面试未通过";
        jobApplicationService.updateApplicationStatus(interview.getApplicationId(), applicationStatus, note);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelInterview(Long id) {
        // 获取面试记录
        Interview interview = interviewMapper.selectById(id);
        if (interview == null) {
            throw new RuntimeException("面试记录不存在");
        }

        // 更新状态
        interview.setStatus(3); // 已取消状态
        interviewMapper.updateById(interview);

        // 更新申请状态
        jobApplicationService.updateApplicationStatus(interview.getApplicationId(), 0, "面试已取消");
    }

    /**
     * 将实体转换为VO
     */
    private InterviewVO convertToVO(Interview interview) {
        InterviewVO vo = new InterviewVO();
        BeanUtils.copyProperties(interview, vo);

        // 设置申请信息
        JobApplication application = jobApplicationMapper.selectById(interview.getApplicationId());
        if (application != null) {
            vo.setApplication(jobApplicationService.getApplicationDetail(application.getId()));
        }

        return vo;
    }
} 